"use strict";

/* Controllers */

app.controller("addNeedCtrl", [
    "$scope",
    "$http",
    "$modal",
    "$log",
    "$location",
    "$stateParams",
    "$rootScope",
    "$anchorScroll",
    "lodash",
    function (
        $scope,
        $http,
        $modal,
        $log,
        $location,
        $stateParams,
        $rootScope,
        $anchorScroll,
        lodash,
    ) {
        $rootScope.initBreadcrumb($scope.breadcrumb);
        //页面加载时，给headerElement设置元素
        $rootScope.initHeaderElements($scope.settings);
        var backUrl = {
            show: true,
            label: "返回",
            func: function () {
                $rootScope.backHistory();
            }
        };
        var add = {
            show: true,
            label: "保存",
            btnId: "saveIssueBtn",
            func: function () {
                $scope.saveNeed();
            }
        };
        var isAdmin = $rootScope.isUserCanOperateByRole("admin");
        $scope.settings.btnEle.push(add);
        $scope.settings.btnEle.push(backUrl);
        // 给部门评定--评定人设置disabled
        $scope.isNeedMaster = $rootScope.isUserCanOperateByRole("dept_charger") ? false : true;
        $scope.breadcrumb.push("需求管理", $scope.type == "add" ? "新增需求" : "编辑需求");

        $scope.type = $stateParams.type == "add" ? "add" : $stateParams.type;

        $scope.isMaster = $rootScope.isUserCanOperateByRole("dept_charger");
        $scope.isPdm = $rootScope.isUserCanOperateByRole("pdm");
        $scope.info = {
            need: {},
            pdmCount: 0,
            qtCount: 0,
            htCount: 0,
            testCount: 0,
            isRepeatPage: false,
            issueList: [], //用户故事集合
            needMasterList: [],//部门评审权限人员集合
            pdmList:[],//pdm类人员集合
            userList:[], // 全部用户
            open: {
                progress: true, // 进展
                sys: true,
                department: true // 部门
            },

        };
        //基础内容的可编辑与只读切换
        $scope.info.basicReadOnly = true //初值是只读为假

        getDataType();
        getUserList();
        getUserList("pdm");
        getUserList("dept_charger");
        if ($scope.type == "add") {
            $scope.info.basicReadOnly = false;
        } else {
            getNeedDetails();
        }

        // 获取需求详情数据
        function getNeedDetails() {
          if (!$stateParams.id) {
            $rootScope.toasterErrorInfo("id未定义，请重试！");
            return false;
          }
          var url = matrix_product_url + "/need/getNeeds?id=" + $stateParams.id + "&isPage=true&isOnline=true";
          $http.get(url).success(function(result) {
            if (result.code == "0") {
              $scope.info.need = result.data[0];
              $scope.info.need.fallbackReason2 = angular.copy($scope.info.need.fallbackReason);

              /**
               * 以下是基础信息部分
               */
              //获取需求来源分类
              $scope.info.need.sltSource = lodash.findWhere($scope.info.sources, {key: $scope.info.need.source});

              //提出人信息
              $scope.info.need.sltCreator = { crtname: $scope.info.need.proposerName, realname: $scope.info.need.proposerName, account: $scope.info.need.proposerAccount };

                // 根据来源类型 获取对应的部分信息
              if ($scope.info.need.source == "CUSTOMER") {
                //客户名
                if ($scope.info.need.customerName && $scope.info.need.customerCode) {
                  $scope.info.need.customers = { show: true };
                  $scope.info.need.customers.selCustomer = { crtname: $scope.info.need.customerCode + " " + $scope.info.need.customerName };
                }
              } else if ($scope.info.need.source == "WORKERORDER") {
                //工单号
                if ($scope.info.need.ticketNumber) {
                  $scope.info.need.workOrder = { show: true, ticketNumber: $scope.info.need.ticketNumber, content: ticketed_url };
                }
              } else {
                //需求部门
                if ($scope.info.need.needDept) {
                  $scope.info.need.departments = { show: true };
                  var needDept = $scope.info.need.needDept;
                  var dept = config_need_departments.filter(function(
                    a
                  ) {
                    return a.type == needDept;
                  })[0];
                  $scope.info.need.departments.selDepartment = dept;
                }
              }

                /**
                 * 以下是部门评审
                 */
                //是否需要培训
                $scope.info.need.departmentTrain = $scope.info.need.deptTrain == "1" ? true : false;
                $scope.info.need.lossPrevent = { isChecked: $scope.info.need.reduceLoss > 0 ? true : false }
                $scope.info.need.mayProfit = { isChecked: $scope.info.need.profit > 0 ? true : false }
                $scope.info.need.saveCost = { isChecked: $scope.info.need.expectLowerCostList.length > 0 ? true : false }
                //部门评定人默认是当前用户
                if (!$scope.info.need.deptChargeAccount || $scope.info.need.deptChargeAccount == "") {
                  if ($scope.info.need.status == "NO_ACCEPT" && !$scope.isMaster) {
                    $scope.info.need.sltDepartment = "";
                  } else {
                    $scope.info.need.sltDepartment = { crtname: getUserName(), realname: getUserName(), account: getUserAccount() };
                  }
                } else {
                  $scope.info.need.sltDepartment = {
                      crtname: $scope.info.need.deptChargeName,
                      realname: $scope.info.need.deptChargeName,
                      account: $scope.info.need.deptChargeAccount };
                }

                /**
                 * 以下是pdm部分
                 * @type {*|string}
                 */
              //回退理由拆分成数组
              var fallbackReason = $scope.info.need.fallbackReason;
              if (fallbackReason) {
                var split = fallbackReason.split(",");
                $scope.info.returns.forEach(function(a) {
                  split.forEach(function(b) {
                    if (a.value == b) {
                      a.checked = true;
                    }
                  });
                });
              }
              //是否回退
              $scope.info.need.pdmIsReturn = $scope.info.need.isFallback == "1" ? true : undefined;
              //是否完成
              $scope.info.need.isComplete = $scope.info.need.isComplete == "1" ? true : undefined;
              //选中其他时的备注
              $scope.info.need.sltItemValue = $scope.info.need.otherPurposes || "";
              $scope.info.need.pdmEndDate = Date.parse(new Date());

              //用户故事
              $scope.info.issueList = $scope.info.need.issues;

              // 锚点设置
              var noAccept = $scope.info.need.status == "NO_ACCEPT" ? true : false;
              var accept = $scope.info.need.status == "ACCEPT" ? true : false;
              if ($scope.isMaster && noAccept) {
                $location.hash("dept");
                $anchorScroll();
              } else if ($scope.isPdm && accept) {
                $location.hash("pdm");
                $anchorScroll.yOffset = 40;
                $anchorScroll();
              }
            } else {
              $rootScope.toasterErrorInfo("获取需求数据详情异常，请联系管理员！");
            }
          });
        }

        $scope.info.showReduceLoss = false;

        // 获取不同类型的用户数据
        function getUserList(type) {
          var url = beetle_auth_url + "/user/?token_id=" + getTokenId();
          if (type) {
            url = url + "&role_name=" + type;
          }
          $http.get(url).success(function(result) {
            if (result.success) {
              if (result.data) {
                angular.forEach(result.data, function(user) {
                  user.crtname = user.realname;
                });
                if (type == "dept_charger") {
                  $scope.info.needMasterList = result.data;
                } else if (type == "pdm") {
                  $scope.info.pdmList = result.data;
                } else {
                  $scope.info.userList = result.data;
                }
              } else {
                $rootScope.toasterErrorInfo("获取用户数据错误！");
              }
            } else {
              $rootScope.toasterErrorInfo(result.msg);
            }
          });
        }

        // 切换switch
        $scope.changeSwitch = function (deptTrain) {
            $scope.info.need.deptTrain = deptTrain;
        };

        // 判断是否有相同元素
        function isRepeat(arr) {
            return /(\x0f[^\x0f]+)\x0f[\s\S]*\1/.test(
                "\x0f" + arr.join("\x0f\x0f") + "\x0f"
            );
        }


        // 保存need数据
        $scope.saveNeed = function() {
          if (!$scope.info.need.title) {
            $rootScope.toasterWarningInfo("需求标题不能为空！");
            return false;
          }

          if (!$scope.info.need.sltSource) {
            $rootScope.toasterWarningInfo("需求来源不能为空！");
            return false;
          }


          if (!$scope.info.need.needDesc) {
            $rootScope.toasterWarningInfo("需求简述不能为空！");
            return false;
          }

          if ($scope.info.need.customers) {
            if ($scope.info.need.customers.show) {
              $scope.info.need.departments = { show: false };
              $scope.info.need.workOrder = { show: false };
              var selCustomer = $scope.info.need.customers.selCustomer;
              if (selCustomer == "" || selCustomer == undefined || selCustomer == null) {
                $rootScope.toasterWarningInfo("客户的名称不能为空");
                return false;
              }
            }
          }
          if ($scope.info.need.departments) {
            if ($scope.info.need.departments.show) {
              $scope.info.need.customers = { show: false };
              $scope.info.need.workOrder = { show: false };
              var selDepartment = $scope.info.need.departments.selDepartment;
              if (selDepartment == "" || selDepartment == undefined || selDepartment == null) {
                $rootScope.toasterWarningInfo("部门的名称不能为空");
                return false;
              }
            }
          }

          if ($scope.info.need.workOrder) {
            if ($scope.info.need.workOrder.show) {
              $scope.info.need.departments = { show: false };
              $scope.info.need.customers = { show: false };
              var content = $scope.info.need.workOrder.content;
              if (content == "" || content == undefined || content == null) {
                $rootScope.toasterWarningInfo("工单的内容不能为空");
                return false;
              }
            }
          }

            if ($scope.info.need.lossPrevent) {
                if ($scope.info.need.lossPrevent.isChecked) {
                    if ($scope.info.need.reduceLoss == 0) {
                        $rootScope.toasterWarningInfo("此处的预防损失应该大于0");
                        return false;
                    }
                }
            }

          if ($scope.info.need.mayProfit) {
              if ($scope.info.need.mayProfit.isChecked) {
                  if ($scope.info.need.profit == 0) {
                      $rootScope.toasterWarningInfo("此处的可能盈利应该大于0");
                      return false;
                  }
              }
          }

          if ($scope.info.need.saveCost) {
              if ($scope.info.need.saveCost.isChecked) {
                  var expectLowerCostList = $scope.info.need.expectLowerCostList;
                  if (expectLowerCostList.length >= 1) {
                      var userNum = expectLowerCostList[0].userNum;
                      var hours = expectLowerCostList[0].hours;
                      if (userNum == 0 || hours == 0) {
                          $rootScope.toasterWarningInfo("请注意节约成本的内容，不能为0");
                          return false;
                      }
                  }
              }
          }

          //处理需求目的集合
          var purpose = "";
          angular.forEach($scope.info.need.sltObj, function(obj) {
            purpose += obj.key + ($scope.info.need.sltObj.length == obj + 1 ? "" : ",");
          });

          var postParams=$scope.info.need
          postParams.createrName=getUserName(),
          postParams.createrAccount=getUserAccount(),
          postParams.source=$scope.info.need.sltSource ? $scope.info.need.sltSource.key : "",
          postParams.proposerAccount=$scope.info.need.sltCreator ? $scope.info.need.sltCreator.account : "",
          postParams.proposerName=$scope.info.need.sltCreator ? $scope.info.need.sltCreator.realname : "",
          postParams.followAccount=$scope.info.need.sltPdm ? $scope.info.need.sltPdm.account : "",
          postParams.followName=$scope.info.need.sltPdm ? $scope.info.need.sltPdm.realname : "",
          postParams.purpose=purpose ? purpose : $scope.info.need.purpose,
          postParams.deptChargeName=$scope.info.need.sltDepartment ? $scope.info.need.sltDepartment.realname : "",
          postParams.deptChargeAccount=$scope.info.need.sltDepartment ? $scope.info.need.sltDepartment.account : "",
          postParams.deptPriority=$scope.info.need ? $scope.info.need.deptPriority || 0 : 0,
          postParams.deptTrain=$scope.info.need.departmentTrain ? 1 : 0,
          postParams.reduceLoss=$scope.info.need.reduceLoss || 0,
          postParams.profit=$scope.info.need.profit || 0,
          postParams.otherPurposes=$scope.info.need.sltItemValue || "",
          postParams.star=0
          postParams.expectLowerCostList = $scope.info.need.expectLowerCostList? $scope.info.need.expectLowerCostList:[]
          postParams.expectLowerCost=""
          //部门
          if ($scope.info.need.departments) {
            if ($scope.info.need.departments.selDepartment) {
              postParams.needDept = $scope.info.need.departments.selDepartment.type;
            }
          }
          //客户
          if ($scope.info.need.customers) {
            if ($scope.info.need.customers.selCustomer) {
              if ($scope.info.need.customers.selCustomer.crtname) {
                var crtname = $scope.info.need.customers.selCustomer.crtname;
                var split = crtname.split(" ");
                postParams.customerCode = split[0];
                postParams.customerName = split[1];
              }
            }
          }
          //工单
          if ($scope.info.need.workOrder) {
            if ($scope.info.need.workOrder.ticketNumber) {
              postParams.ticketNumber = $scope.info.need.workOrder.ticketNumber;
              postParams.ticketUrl = $scope.info.need.workOrder.content + $scope.info.need.workOrder.ticketNumber;
            }
          }


          if ($scope.info.need) {
            postParams.id = $scope.info.need ? $scope.info.need.id : "";
          }

          if ($scope.isPdm || isAdmin) {
            postParams.needPdm = $scope.info.need.needPdm || [];
            postParams.reviewUpdateTime = timestampToTime(Date.parse($scope.info.need.pdmEndDate), true);
            postParams.pdmNeedType = $scope.info.need ? $scope.info.need.pdmNeedType : "";
            postParams.isFallback = $scope.info.need.pdmIsReturn ? 1 : 0;
            postParams.isComplete = $scope.info.need.isComplete ? 1 : 0;
            postParams.pdmClearTime = timestampToTime(Date.parse($scope.info.need.pdmClearTime), true);
            postParams.cycleStatus = $scope.info.need.sltCycleStatus ? $scope.info.need.sltCycleStatus.value || "day" : "day";

            saveParams(postParams);
          } else {
            saveParams(postParams);
          }
        };

        function saveParams(postParams) {
            $("#saveIssueBtn").attr("disabled", true);
            var url = matrix_product_url + "/need/saveNeed";
            $http({
                method: "post",
                url: url,
                data: JSON.stringify(postParams),
                headers: {"Content-Type": "application/json"}
            }).success(function (result) {
                if (result.code == "0") {
                    if ($scope.isPdm) {
                        if ($scope.info.issueList.length > 0) {
                            saveIssue();
                        } else {
                            window.location.href =
                                "#/app/need/list/" +
                                ($stateParams.accept || "") +
                                "/" +
                                ($stateParams.appointAccept || "");
                            $rootScope.toasterSuccessInfo("保存成功！");
                        }
                    } else {
                        window.location.href =
                            "#/app/need/list/" +
                            ($stateParams.accept || "") +
                            "/" +
                            ($stateParams.appointAccept || "");
                        $rootScope.toasterSuccessInfo("保存成功！");
                    }
                } else {
                    $rootScope.toasterErrorInfo(result.desc);
                }
                $("#saveIssueBtn").attr("disabled", false);
            });
        }

        // 保存issue
        function saveIssue() {
          var paramsArray = new Array();
          angular.forEach($scope.info.issueList, function(issue) {
            var issueItem = { needId: $stateParams.id, number: issue.number || "", creatorAccount: getUserAccount(), creatorName: getUserName(), groupTag: issue.sltTagGroup || "", user: issue.sltUser ? issue.sltUser.name : "", toAccount: issue.sltToAccount ? issue.sltToAccount.account : "", action: issue.action || "", status: "INHAND" };
            if (issue.id) {
              issueItem.id = issue.id;
            }
            paramsArray.push(issueItem);
          });
          var postParams = { issues: paramsArray };
          var url = matrix_product_url + "/issue/saveIssues";
          $http({
            method: "post",
            url: url,
            data: JSON.stringify(postParams),
            headers: { "Content-Type": "application/json" }
          }).success(function(result) {
            if (result.code == "0") {
              window.location.href = "#/app/need/list//";
              $rootScope.toasterSuccessInfo("保存成功！");
            } else {
              $rootScope.toasterErrorInfo(result.desc);
            }
            $("#saveIssueBtn").attr("disabled", false);
          });
        }
        //获取数据类型
        function getDataType() {
            var url = "../data/objectiveState.json";
            $http.get(url).success(function(result) {
                if (result.code == "0") {
                    //退回
                    $scope.info.returns = result.data.RETURN;
                    angular.forEach($scope.info.returns, function(ret) {
                        ret.check = false;
                    });

                    //类型数据
                    $scope.info.brdTypes = result.data.BRDTYPE;
                    angular.forEach($scope.info.brdTypes, function(brdType) {
                        brdType.crtname = brdType.value;
                        if ($scope.info.need.brdType == brdType.key) {
                            $scope.info.need.brdTypeObj = brdType;
                        }
                    });

                    //PDMBRDTYPE类型数据
                    $scope.info.pdmBrdTypes = result.data.PDMBRDTYPE;

                    //系统数据
                    $scope.info.syss = result.data.SYS;
                    angular.forEach($scope.info.syss, function(sys) {
                        sys.check = false;
                    });

                    //板块数据
                    $scope.info.plates = result.data.PLATE;
                    angular.forEach($scope.info.plates, function(plate) {
                        plate.check = false;
                    });
                } else {
                    $rootScope.toasterWarningInfo("获取目的状态有误！");
                }
            });
            //来源数据
            $scope.info.sources = $rootScope.getSysConfigList("NEED_SOURCE");
            angular.forEach($scope.info.sources, function(source) {
                source.crtname = source.value;
                if ($scope.info.need.source == source.key) {
                    $scope.info.need.sourceObj = source;
                }
            });
        }


    }
]);
